<?php
class financeModel extends RPHP_Model
{

    protected $_auth = null;

    //检查权限
    public function checkPriv($pv, $return = true, $menu = true)
    {
        $this->_auth = $this->auth->CheckPriv($pv, $return, $menu);
        return $this->_auth;
    }
    //获取某月的开始时间和结束时间
    public  function getMouthTime($m = "",$y = ""){
        if ($y == "") $y = date("Y");
        if ($m == "") $m = date("m");
        $m = sprintf("%02d", intval($m));
        $y = str_pad(intval($y), 4, "0", STR_PAD_RIGHT);

        $m>12 || $m<1 ? $m=1 : $m=$m;
        $firstday = strtotime($y . $m . "01000000");
        $firstdaystr = date("Y-m-01", $firstday);
        $lastday = strtotime(date('Y-m-d 23:59:59', strtotime("$firstdaystr +1 month -1 day")));

        return array(
            "start_time" => $firstday,
            "end_time" => $lastday
        );
    }
    
    //发放销售奖励
    public function sendOrderAwardMoney($da)
    {
       
       
        $my_order_money = $da['my_order_money'];
        $level_total_money = $da['level_total_money'];
        $subtract_total_order_money = $da['subtract_total_order_money'];
        $team_total_order_money = $da['team_total_order_money'];
        $commission_rate = $da['commission_rate'];
        $award_order_money = number_format($da['award_money'],2,".","");
        $uids = $da['uid'];
        $caid = intval($da['caid']);
        $month = intval($da['month']);
        $cate = $this->table('goods_category')->findByPk($caid,"caid");//分类信息
        if($uids && $commission_rate && $cate['award_json'] && $month ){
            $this->db->begin();
            $commit      = true;
            $time = time();
            //配置信息（发送总金额）
          /* $config =  $this->getSetting();
           $award_order_money = $config['award_order_money'];*/
            $config = json_decode($cate['award_json'],true);
           if(!$award_order_money){
               
               return array("code"=>901,"msg"=>"请输入发放奖励金额");
           }
             $num = 0;
           //print_r($da);die;
            foreach($uids as $v){
                
                //
                $date_time = $this->getMouthTime($month);
                $send_time = $date_time['start_time'];
                
                 $award_log = $this->table("sell_award_log")->findBySql("`caid`=".$caid." AND `send_time`=".$send_time."  AND `uid`=".$v);
                 if(!$award_log && $commission_rate[$v] && $commit){
                    
                     $num +=1;
                     //插入发放记录
                     $se['create_time']  = $time;
                     if($my_order_money[$v]){
                         
                         $se['my_order_money']  = $my_order_money[$v];
                     }
                     
                     if($level_total_money[$v]){
                         
                         $se['level_total_money']  = $level_total_money[$v];
                     }
                     
                     if($subtract_total_order_money[$v]){
                          
                         $se['subtract_total_order_money']  = $subtract_total_order_money[$v];
                     }
                     
                     
                     if($team_total_order_money[$v]){
                          
                         $se['team_total_order_money']  = $team_total_order_money[$v];
                     }




                     $se['capping_money']  = $config['capping_money'];
                     $se['send_time']  = $send_time;
                     $se['total_money'] = $award_order_money;
                     $se['commission_rate']  = $commission_rate[$v];
                     $se['uid'] = $v;
                     $se['caid'] = $caid;
                     $se['send_money'] =number_format($commission_rate[$v]  * $award_order_money,2,".","");
                     if($se['send_money']>$se['capping_money']){

                         $se['send_money'] = $se['capping_money'];

                     }



                     $log_id = $this->table("sell_award_log")->insert($se);
                     
                     if(!$log_id){
                         
                         $commit = false;
                     }
                     
                     if($commit){
                       
                        $balance = $this->table("finance_balance")->findBySql("`uid`=".$v);
                        // 更新资金表
                        $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `ximi_money`=`ximi_money`+" . $se['send_money'] . " WHERE `uid`=" . $balance['uid'];
                        $rcs = $this->sql($sql);
                        if ($rcs > 0) {
                            $detail_note = "获得团队销售奖励";
                            $event       = 26;
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`,`dataid`,`table_name`) VALUES (" . $balance['uid'] . "," . $event . "," . $se['send_money'] . "," . ($balance['ximi_money'] + $se['send_money']) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $log_id . ",'sell_award_log')";
                            $detail_id   = $this->sql($sql);
                            if (!$detail_id) {
        
                                $commit = false;
        
                            }
        
                        }else{
                            $commit = false;
                            
                        }
                         
                         
                     }
                     
                 }
            }
            
            if($commit){
                
               
                $this->db->commit();
                if($num){
                    
                    return array("code"=>200,"msg"=>"发放成功");
                }else{
                    
                    return array("code"=>902,"msg"=>"已发放");
                }
                
                
                
            }else{
                
                $this->db->rollback();
            }
            
        }
        
        return array("code"=>900,"msg"=>"发放失败，请重新发放");
    }

    //获取一级分类
    public function getCate()
    {
      $data =  $this->table("goods_category")->findAllBySql("`stat`=1 AND `fucaid`=0","`caid`,`name`,`award_json`");
      return  $data;
    }

    //销售奖励统计
    public function getOrderAwardDetail($para)
    {
        $data = [];
       if($para['caid']>0 && $para['month']>0){
           $cate = $this->table('goods_category')->findByPk($para['caid'],"caid");//分类信息
           if($cate){

               $date_time = $this->getMouthTime($para['month']);//获取某月的开始时间和结束时间

               //所有下级分类集合
               $caids = $this->getCategoryIds($cate['caid']);

               //所属分类商品id集合
               $goods =  $this->table("goods_data")->findAllBySql("`caid` IN (".$caids.")","`goods_id`,`goods_name`");
               if($goods){

                   $goods_ids = "";//商品id集合
                   foreach($goods as $g){
                       $goods_ids .= empty($goods_ids)?$g['goods_id']:",".$g['goods_id'];

                   }
                   //echo $goods_ids;die;
                   if($goods_ids){
                       //西海代理用户信息
                       $members = $this->table("member_account")->findAllBySql("`member_level`=3 AND `stat`=1","`uid`,`realname`,`mobile`,`name`,`recode`");
                       if($members){
                            global $child;
                            $this->getAllMemberList();
                          
                            //print_r(  $child);die;
                             $total_sales_order_money = 0;//所有西海代理有效销售总额
                          // print_r($members);die;
                            foreach($members as $k=>$m){

                                $user_ids .=empty($user_ids)?$m['uid']:",".$m['uid'];
                                //if($k==0){
                                $child_all =  $this->findAllChild($m['uid']);
                                   // $member_all =  $this->getMemberAllInfo(452);//所有下级信息（包含自己）$m['uid']
                                $member_all['uids'] =$child_all['user_ids'];
                                $member_all['tj_uid'] =$child_all['yi_level_uids'];
                                $member_all['user_id'] =$m['uid'];
                               // }

                                //print_r($member_all);die;
                                 if($member_all){

                                    $orders =  $this->OrderStatistics($goods_ids,$member_all,$cate['award_json'],$date_time);//统计符合条件订单
                                    // print_r($orders);die;
                                     if($orders){
                                           $m['order'] = $orders;
                                           if($orders['status']==1){

                                               $total_sales_order_money  +=$orders['team_total_order_money'];
                                           }

                                           $data[] = $m;


                                     }
                                 }


                            }
                            //print_r($data);die;

                            if($data){

                               foreach($data as $key=>$val){
                                   $commission_rate = 0;
                                    if($val['order']['status']){

                                        $commission_rate=  number_format($val['order']['team_total_order_money'] / $total_sales_order_money,2,".","");

                                    }
                                   $data[$key]['order']['commission_rate'] =$commission_rate;
                                   $data[$key]['order']['total_sales_order_money']  = $total_sales_order_money;
                               }

                            }
                       }

                   }

               }

           }
       }
//print_r($data);die;
       return $data;

    }

    //统计符合条件订单
  public function OrderStatistics($goods_ids="",$member_all=array(),$award_json='',$date_time=array())
  {
      global $child;
    // print_r($child);die;
      $arr = [];
      if($goods_ids && $member_all['uids']  && $date_time){

          $start_time = $date_time['start_time'];//开始时间
          $end_time = $date_time['end_time'];//结束时间
           $uid_ids = implode(',',$member_all['uids']);
           $my_order_money = 0;//自己的销量
           $team_total_order_money = 0;//团队的销量
           $tj_level_total_money = 0;//365等级销量

          //所属商品订单信息
          $sql = "SELECT o.`order_id`,o.`uid`,o.`order_amount`,o.`add_time` FROM {$this->_prefix['primary']}order_info AS o LEFT JOIN {$this->_prefix['primary']}order_goods AS g ON o.`order_id`= g.`order_id`  WHERE  o.`order_status`=7 AND o.`shipping_status`=2 AND o.`pay_status`=2 AND g.goods_id IN (".$goods_ids.") AND o.`uid` IN (".$uid_ids.") AND o.`add_time`>=".$start_time." AND o.`add_time` <".$end_time;//AND o.`add_time`>=".$start_time." AND o.`add_time` <".$end_time
          $rs  = $this->sql($sql);
          if($rs){


              print_r($rs);die;
              $level_total_moeny = [];//所有一级团队销量
               foreach($rs as $r){
                  // echo date("Y-m",$r['add_time']);die;
                   if($r['uid'] == $member_all['user_id']){
                       $my_order_money +=$r['order_amount'];

                   }///else{

                       $team_total_order_money +=$r['order_amount'];
                   //}

                  // print_r($child);die;
                   //最大一级团队销量



                   if($member_all['tj_uid']){

                        if(in_array($r['uid'],$member_all['tj_uid'])){

                            $tj_level_total_money +=$r['order_amount'];
                        }
                   }
     /*              if($member_all['yi_level_arr']){

                       foreach( $member_all['yi_level_arr'] as $k=>$la){

                           if(in_array($r['uid'],$la)){
                               $level_total_moeny[$k] += $r['order_amount'];

                           }

                       }

                   }*/
                    $orders[] = $r;



               }

              $yi_order_money = 0;
              if($child[$member_all['user_id']])
              {

                  foreach($child[$member_all['user_id']] as $rs)
                  {
                      $tm = 0;

                      $myteam[$rs['uid']] = $this->findAllChild($rs['uid'])['user_ids'];
                      $myteam[$rs['uid']][] = $rs['uid'];

                      foreach($orders as $v){

                          if(in_array($v['uid'],$myteam[$rs['uid']])){
                              $tm += $r['order_amount'];

                          }

                      }

                      // 统计团队的业绩
                      if(!$yi_order_money){

                              $yi_order_money = $tm;

                      }else{
                          if($tm >$yi_order_money){
                              $yi_order_money = $tm;

                          }

                      }

                     // echo $yi_order_money;die;

                  }
              }

              //print_r($myteam);die;
              //echo $yi_order_money;die;
               //最大一级团队销量
/*              $yi_order_money = 0;
              if($level_total_moeny){
                  foreach($level_total_moeny as $tm){
                       if(!$yi_order_money){
                           $yi_order_money = $tm;

                       }else{
                           if($tm >$yi_order_money){
                               $yi_order_money = $tm;

                           }

                       }

                  }
              }*/
              //echo $yi_order_money;die;
              //减去大部门销售额
              $subtract_total_order_money =number_format($team_total_order_money-$yi_order_money,2,".","");
              //$commission_rate = 0;

              $arr['subtract_total_order_money'] = $subtract_total_order_money;
              $arr['my_order_money'] = $my_order_money;
              $arr['tj_level_total_money'] = $tj_level_total_money;
              $arr['team_total_order_money'] = $team_total_order_money;
              $arr['status'] = 0;
              if($award_json){
                  //$config = $this->getSetting();


                  $award_config = json_decode($award_json,true);
                  //print_r($award_config);die;
                  //验证自购 seft_money   验证365会员等级re_money  //验证减去大部门销售额  order_money  //验证团队总销量 team_order_money
                  if($my_order_money>=$award_config['seft_money'] && $tj_level_total_money >=$award_config['re_money'] && $subtract_total_order_money >=$award_config['order_money'] && $team_total_order_money >= $award_config['team_order_money']){

                      $arr['status'] = 1;

                  }

              }

          }

      }
     //print_r($arr);die;
      return $arr;

  }

  //获取所有的下级信息
    public function getMemberAllInfo($uid,$level = 1,$data=array())
    {

        $rows = $this->table('member_account')->findAllBySql("stat=1 and pid  IN (".$uid.")","`uid`,`name`,`pid`,`member_level`");
        if($level==1){

            $data['uids'][] =$uid;
            $data['user_id'] =$uid;
        }
        $uid = "";
        if($rows){

            foreach($rows as $r){
                $uid .=empty($uid)?$r['uid']:",".$r['uid'];
                if($r['member_level']==1){

                    $data['tj_uid'][] = $r['uid'];//365e等级用户
                }
                if ($level == 1) {
                    $data['yi_level'][$r['uid']] = $r['uid'];//所有的一级用户
                    $data['yi_level_arr'][$r['uid']][] = $r['uid'];
                }

                if( $data['yi_level'][$r['pid']]){
                   /* if(empty($data['yi_level_arr'][$r['pid']])){

                        $data['yi_level_arr'][$r['pid']][] = $r['pid'];
                    }*/
                    $data['yi_level_arr'][$r['pid']][] = $r['uid'];//一级用户对应的团队信息

                }

                $data['level'][$r['uid']] = $level;
                $data['uids'][]           = $r['uid'];//团队所有用户（包含自己）


            }

            $data                     = $this->getMemberAllInfo($uid, $level + 1, $data);
        }

        return $data;

    }

   public  function findAllChild($uid=0,$data = false)
    {
        global $child;

        if($child[$uid])
        {
            foreach($child[$uid] as $r)
        {
            $data['user_ids'][] = $r['uid'];

            if($r['member_level']==1){

                $data['yi_level_uids'][] =  $r['uid'];
            }

            if($child[$r['uid']])
            {
                $data= $this->findAllChild($r['uid'],$data);
            }
        }
    }

        return $data;
    }

/*    public function teamAllChild($uid=0,$data = false)
    {

        $uid = 5;
        global $child;
        if($child[$uid])
        {
            foreach($child[$uid] as $r)
            {
                $myteam[$r['uid']] = $this->findAllChild($r['uid']);
               // $myteam[$r['uid'][] = $r['uid'];

                // 统计团队的业绩

            }
        }
    }*/
    public function getAllMemberList(){
        // 获取所有会员
        global $child;
        $tmp = $this->table('member_account')->findAllBySql("stat<3 ORDER BY `uid` DESC","`uid`,`name`,`pid`,`member_level`");
        if ($tmp) {

            foreach ($tmp as $r) {
                $users[$r['uid']] = $r;
                if($r['pid']>0)
                {
                    $child[$r['pid']][] = $r;
                }
            }

        }

    }





    //获取所有的下级信息
    public function getMemberAllInfo_bf($uid,$level = 1,$data=array())
    {

        $rows = $this->table('member_account')->findAllBySql("stat=1 and pid =".$uid,"`uid`,`name`,`pid`,`member_level`");
        if($level==1){

            $data['uids'][] =$uid;
            $data['user_id'] =$uid;
        }

        if($rows){

            foreach($rows as $r){

                if($r['member_level']==1){

                    $data['tj_uid'][] = $r['uid'];//365e等级用户
                }
                if ($level == 1) {
                    $data['yi_level'][$r['uid']] = $r['uid'];//所有的一级用户
                    $data['yi_level_arr'][$r['uid']][] = $r['uid'];
                }

                if( $data['yi_level'][$r['pid']]){
                    /* if(empty($data['yi_level_arr'][$r['pid']])){

                         $data['yi_level_arr'][$r['pid']][] = $r['pid'];
                     }*/
                    $data['yi_level_arr'][$r['pid']][] = $r['uid'];//一级用户对应的团队信息

                }

                $data['level'][$r['uid']] = $level;
                $data['uids'][]           = $r['uid'];//团队所有用户（包含自己）
                $data                     = $this->getMemberAllInfo($r['uid'], $level + 1, $data);

            }
        }

        return $data;

    }

    //获取所有下级分类id
    public function getCategoryIds($cat_id=0,$data='')
    {

        $rows = $this->table('goods_category')->findAllBySql("stat=1 and fucaid =".$cat_id,"`caid`,`name`");
        if(empty($data)){
            $data = $cat_id;

        }

        if($rows){

            foreach($rows as $r){
                if ($r['caid']) {
                    $data .=empty($data) ?$r['caid']:",".$r['caid'];
                    $data                     = $this->getCategoryIds($r['caid'], $data);
                }

            }
        }
        return $data;
    }
    //获取会员开通记录

    public function getMemberPayinfoList($para, $page = 1, $pagesize = 20)
    {

        $where = '1=1';

        if ($para) {

            if ($para['keyword'] != '') {
                if (is_numeric($para['keyword'])) {

                    $sql = "SELECT * FROM {$this->_prefix['primary']}member_payinfo WHERE `code` = '" . $para['keyword'] . "'";
                    $re  = $this->db->getrow($sql);
                    if (!empty($re)) {

                        $sql = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `recode`='" . $para['keyword'] . "' ";
                        $uid = $this->db->getone($sql);
                        if ($uid > 0) {
                            $where .= " AND b.pid=" . $uid;
                        }
                    } else {

                        $where .= " AND (a.`order_sn`= '" . $para['keyword'] . "' OR a.`code`='" . $para['keyword'] . "'  OR a.`transaction_id` ='" . $para['keyword'] . "' OR a.`tao_mobile`= '" . $para['keyword'] . "' OR b.`mobile`='" . $para['keyword'] . "' OR b.`uid` = '" . $para['keyword'] . "') ";
                    }
                } else {
                    $where .= " AND  (b.`realname` LIKE '%" . $para['keyword'] . "%' OR b.`name` LIKE '%" . $para['keyword'] . "%' OR a.`tao_name`= '" . $para['keyword'] . "'  ) ";
                }

            }

            if (isset($para['order_type'])) {
                $where .= " AND a.`order_type` = " . $para['order_type'];
            }

            if (isset($para['is_received'])) {
                $where .= " AND a.`is_received` = " . $para['is_received'];
            }

            if (isset($para['shipping_status'])) {
                $where .= " AND a.`shipping_status` = " . $para['shipping_status'];
            }

            if (isset($para['pay_status'])) {
                $where .= " AND a.`pay_status` = " . $para['pay_status'];
            }

            if ($para['start_time']) {

                $where .= " AND a.`ctime` >=" . $para['start_time'];
                $para['start_time'] = date("Y-m-d", $para['start_time']);
            }

            if ($para['end_time']) {

                $where .= " AND a.`ctime` <" . $para['end_time'];
                $para['end_time'] = date("Y-m-d", $para['end_time']);
            }
        }
        //echo $where;die;

        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}member_payinfo AS a LEFT JOIN {$this->_prefix['primary']}member_account AS b ON a.`uid`=b.`uid`  WHERE " . $where;
        $cnt = $this->db->getone($sql);

        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = " a.`order_id` DESC";

            $sql = "SELECT a.*,b.`mobile`,b.`realname`,b.`name`,b.`uid` FROM {$this->_prefix['primary']}member_payinfo AS a LEFT JOIN {$this->_prefix['primary']}member_account AS b ON a.`uid`= b.`uid`  WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);

            if ($rs) {
                foreach ($rs as &$val) {

                    $uids[$val['uid']] = $val['uid'];

                    if (!$val['order_type']) {

                        $val['order_type'] = "<span class='label label-success'>开通会员</span>";
                    } else {
                        $val['order_type'] = "<span class='label label-primary'>续费会员</span>";
                    }

                    if ($val['uid']) {
                        //获取用户昵称
                        $user_info = $this->getUsers($val['uid']);

                        $val['user_name'] = $user_info['realname'];

                        if ($user_info['headimgurl'] > 0) {
                            $doc               = $user_info['headimgurl'];
                            $val['headimgurl'] = $this->getDocs($doc);
                            $val['headimgurl'] = $val['headimgurl'][$user_info['headimgurl']];
                        } else {
                            $val['wechat_headimgurl'] = $user_info['wechat_headimgurl'];
                        }
                    }

                    if ($val['tao_province_id'] > 0) {
                        $region[] = $val['tao_province_id'];
                    }

                    if ($val['tao_city_id'] > 0) {
                        $region[] = $val['tao_city_id'];
                    }

                    if ($val['tao_county_id'] > 0) {
                        $region[] = $val['tao_county_id'];
                    }

                }

                if ($region) {
                    $sql = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `region_id` IN (" . implode(",", array_unique($region)) . ")";
                    $tmp = $this->sql($sql);
                    if ($tmp) {
                        foreach ($tmp as $r) {
                            $region[$r['region_id']] = $r['region_name'];
                        }
                    }
                }

            }

            return array(
                'page'    => $page,
                'maxpage' => ceil($cnt / $pagesize),
                'count'   => $cnt,
                'data'    => $rs,
                'para'    => $para,
                'region'  => $region,
            );

        }
    }

    //获取待入账记录
    public function getDRZ($para, $page, $pagesize = 20)
    {
        $where = " 1";
        if ($para) {

            if ($para['type']) {
                $where .= " AND fd.`type`=" . $para['type'];
            }
            if ($para['uid']) {
                $where .= " AND fd.`uid`=" . $para['uid'];
            }

            if ($para['start_time']) {
                $where .= " AND fd.`create_time` >=" . $para['start_time'];

                $para['start_time'] = date("Y-m-d", $para['start_time']);
            }

            if ($para['end_time']) {
                $where .= " AND fd.`create_time` <" . $para['end_time'];

                $para['end_time'] = date("Y-m-d", $para['end_time']);
            }

            if ($para['keyword'] != '') {
                if (is_numeric($para['keyword'])) {
                    $where .= " AND (ma.`mobile`= '" . $para['keyword'] . "' OR ma.`recode`='" . $para['keyword'] . "')";
                } else {
                    $where .= " AND  (ma.`realname` LIKE '%" . $para['keyword'] . "%' OR ma.`name` LIKE '%" . $para['keyword'] . "%')";
                }
            }
        }

        $sql = "SELECT COUNT(fd.`id`) AS `cnt` FROM {$this->_prefix['primary']}finance_drz AS fd LEFT JOIN {$this->_prefix['primary']}member_account AS ma ON ma.`uid`= fd.`uid`  WHERE " . $where;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "fd.`id` DESC";

            $sql = "SELECT fd.*,ma.`mobile`,ma.`realname`,ma.`name`,ma.`recode` FROM {$this->_prefix['primary']}finance_drz AS fd LEFT JOIN {$this->_prefix['primary']}member_account AS ma ON ma.`uid`= fd.`uid`  WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);
            if ($rs) {
                foreach ($rs as $k => $r) {
                    if ($r['uid']) {
                        //获取用户昵称
                        $user_info = $this->getUsers($r['uid']);

                        $rs[$k]['user_name'] = $user_info['realname'];

                        if ($user_info['headimgurl'] > 0) {
                            $doc                  = $user_info['headimgurl'];
                            $r['headimgurl']      = $this->getDocs($doc);
                            $rs[$k]['headimgurl'] = $r['headimgurl'][$user_info['headimgurl']];
                        } else {
                            $rs[$k]['wechat_headimgurl'] = $user_info['wechat_headimgurl'];
                        }
                    }

                }

            }
        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
        );
    }

    //获取会员收支明细
    public function getFinanceDetail($para, $page, $pagesize = 20)
    {
        $where = " 1";
        if ($para) {

            if ($para['event']) {
                $where .= " AND fd.`event`=" . $para['event'];
            }
            if ($para['uid']) {
                $where .= " AND fd.`uid`=" . $para['uid'];
            }

            if ($para['start_time']) {
                $where .= " AND fd.`create_time` >=" . $para['start_time'];

                $para['start_time'] = date("Y-m-d", $para['start_time']);
            }

            if ($para['end_time']) {
                $where .= " AND fd.`create_time` <" . $para['end_time'];

                $para['end_time'] = date("Y-m-d", $para['end_time']);
            }

            if ($para['keyword'] != '') {
                if (is_numeric($para['keyword'])) {
                    $where .= " AND (ma.`mobile`= '" . $para['keyword'] . "' OR ma.`recode`='" . $para['keyword'] . "')";
                } else {
                    $where .= " AND  (ma.`realname` LIKE '%" . $para['keyword'] . "%' OR ma.`name` LIKE '%" . $para['keyword'] . "%')";
                }
            }
        }

        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}finance_detail AS fd LEFT JOIN {$this->_prefix['primary']}member_account AS ma ON ma.`uid`= fd.`uid`  WHERE " . $where;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "fd.`create_time` DESC,fd.`id` DESC";

            $sql = "SELECT fd.*,ma.`mobile`,ma.`realname`,ma.`name`,ma.`recode` FROM {$this->_prefix['primary']}finance_detail AS fd LEFT JOIN {$this->_prefix['primary']}member_account AS ma ON ma.`uid`= fd.`uid`  WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);
            if ($rs) {
                foreach ($rs as $k => $r) {
                    if ($r['uid']) {
                        //获取用户昵称
                        $user_info = $this->getUsers($r['uid']);

                        $rs[$k]['user_name'] = $user_info['realname'];

                        if ($user_info['headimgurl'] > 0) {
                            $doc                  = $user_info['headimgurl'];
                            $r['headimgurl']      = $this->getDocs($doc);
                            $rs[$k]['headimgurl'] = $r['headimgurl'][$user_info['headimgurl']];
                        } else {
                            $rs[$k]['wechat_headimgurl'] = $user_info['wechat_headimgurl'];
                        }
                    }

                }

            }
        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
        );
    }

    public function getMemberPayinfoOne($order_id)
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}member_payinfo WHERE `order_id`=" . $order_id . " AND `pay_status`=2";
        $data = $this->db->getrow($sql);
        if ($data) {

            if ($data['pid']) {
                $uids[] = $data['pid'];

            }

            if ($data['out_money_one_id']) {
                $uids[] = $data['out_money_one_id'];

            }

            if ($data['out_money_two_id']) {

                $uids[] = $data['out_money_two_id'];
            }

            if ($data['out_money_three_id']) {
                $uids[] = $data['out_money_three_id'];

            }
            $member = array();
            $sql    = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `recode`='" . $data['code'] . "'";
            $users  = $this->db->getrow($sql);
            $sql    = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $data['uid'];
            $u      = $this->db->getrow($sql);

            if (!empty($uids)) {
                $sql = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid` IN (" . implode(",", $uids) . ")";
                $us  = $this->sql($sql);

                foreach ($us as $val) {

                    $member[$val['uid']] = $val['uid'] . "-" . $val['name'];

                }
            }

            $data['user']   = $users;
            $data['u']      = $u;
            $data['member'] = $member;

        }

        return $data;
    }

    // 获取系统所有注册会员
    public function getAllMember($para)
    {
        $where = " `stat`=1 ";
        if ($para['info']) {
            if (is_numeric($para['info'])) {

                $where .= " AND `recode`='" . $para['info'] . "'";
            } else {
                $where .= " AND (`name` LIKE '%" . $para['info'] . "%')";

            }

            $sql = "SELECT `uid`,`name` FROM {$this->_prefix['primary']}member_account WHERE " . $where;
            return $this->sql($sql);
        }

    }

    //退单操作

    public function saveReturnOrder($da)
    {

        $code     = 900;
        $order_id = intval($da['order_id']);
        $uid      = intval($da['uid']);

        $field['pid']       = empty($da['pid']) ? 0 : explode('-', $da['pid'])[0];
        $out_money_one_id   = empty($da['pid_one']) ? 0 : explode('-', $da['pid_one'])[0];
        $out_money_two_id   = empty($da['pid_two']) ? 0 : explode('-', $da['pid_two'])[0];
        $out_money_three_id = empty($da['pid_three']) ? 0 : explode('-', $da['pid_three'])[0];
        $out_money_one      = intval($da['money_one']);
        $out_money_two      = intval($da['money_two']);
        $out_money_three    = intval($da['money_three']);
        $field['remark']    = addslashes(htmlspecialchars(trim($da['remark'])));
        if ($out_money_one_id > 0 && $out_money_one > 0 && $uid > 0) {
            $field['out_money_one_id'] = $out_money_one_id;
            $field['out_money_one']    = $out_money_one;
        }

        if ($out_money_two_id > 0 && $out_money_two > 0) {
            $field['out_money_two_id'] = $out_money_two_id;
            $field['out_money_two']    = $out_money_two;
        }

        if ($out_money_three_id > 0 && $out_money_three > 0) {
            $field['out_money_three_id'] = $out_money_three_id;
            $field['out_money_three']    = $out_money_three;
        }
        $field['order_status'] = 2;
        $field['return_time']  = time();
        if ($order_id > 0 && $field['pid'] > 0 && $uid > 0) {
            $this->db->begin();
            $commit      = false;
            $code        = 403;
            $member_data = $this->getUsers($uid);

            //修改注册订单
            $sql = "UPDATE {$this->_prefix['primary']}member_payinfo SET ";

            foreach ($field as $key => $value) {
                $upsql[] = "`" . $key . "`='" . $value . "'";
            }
            $sql .= implode(",", $upsql) . " WHERE `order_id`=" . $order_id;
            $rcnum = $this->sql($sql);

            if ($rcnum) {
                //查出所有直推下级
                /*  $sql        = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `pid`=" . $uid . " AND `stat`<3";
                $users         = $this->sql($sql); */
                /*         $uids = '';
                foreach($users as $val){
                $uids  .= empty($uids)?$val['uid']:','.$val['uid'];

                }
                $uids = trim($uids); */
                //禁用用户
                $sql = "UPDATE {$this->_prefix['primary']}member_account SET `stat`=2,`update_time`=" . time() . " WHERE `uid`=" . $uid;
                $ru  = $this->sql($sql);

                $sql = "DELETE FROM {$this->_prefix['primary']}member_online WHERE `uid`=" . $uid;
                $rds = $this->sql($sql);

                if ($ru) {
                    //修改所有直推下级  的父级
                    $sql = "UPDATE {$this->_prefix['primary']}member_account SET `pid`=" . $field['pid'] . ",`update_time`=" . time() . " WHERE `pid`= " . $uid;
                    $rp  = $this->sql($sql);

                    if ($rp) {
                        $status = true;
                        //扣除人员奖金
                        if ($field['out_money_one_id'] > 0) {

                            $sql  = "UPDATE {$this->_prefix['primary']}finance_balance SET `money` =`money`-" . $field['out_money_one'] . ",`revenue`=`revenue`-" . $field['out_money_one'] . " WHERE `uid`=" . $field['out_money_one_id'];
                            $rep1 = $this->sql($sql);
                            if ($rep1) {
                                $member_money1 = $this->getUserMoney($field['out_money_one_id']);
                                //插入资金明细
                                $detail_note = '[' . $member_data['name'] . '] 退单扣除奖励' . $field['out_money_one'];
                                $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`freeze`,`create_time`,`note`) VALUES (" . $field['out_money_one_id'] . ",11," . $field['out_money_one'] . "," . $member_money1['money'] . "," . ($member_money1['freeze']) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "')";
                                $detail_id   = $this->sql($sql);
                                if (!$detail_id) {
                                    $status = false;

                                }
                            }
                        }

                        if ($field['out_money_two_id'] > 0) {

                            $sql  = "UPDATE {$this->_prefix['primary']}finance_balance SET `money` =`money`-" . $field['out_money_two'] . ",`revenue`=`revenue`-" . $field['out_money_two'] . " WHERE `uid`=" . $field['out_money_two_id'];
                            $rep2 = $this->sql($sql);
                            if ($rep2) {
                                $member_money2 = $this->getUserMoney($field['out_money_two_id']);
                                //插入资金明细
                                $detail_note = '[' . $member_data['name'] . '] 退单扣除奖励' . $field['out_money_two'];
                                $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`freeze`,`create_time`,`note`) VALUES (" . $field['out_money_two_id'] . ",11," . $field['out_money_two'] . "," . $member_money2['money'] . "," . ($member_money2['freeze']) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "')";
                                $detail_id   = $this->sql($sql);
                                if (!$detail_id) {
                                    $status = false;

                                }
                            }
                        }

                        if ($field['out_money_three_id'] > 0) {

                            $sql  = "UPDATE {$this->_prefix['primary']}finance_balance SET `money` =`money`-" . $field['out_money_three'] . ",`revenue`=`revenue`-" . $field['out_money_three'] . " WHERE `uid`=" . $field['out_money_three_id'];
                            $rep3 = $this->sql($sql);
                            if ($rep3) {
                                $member_money3 = $this->getUserMoney($field['out_money_three_id']);
                                //插入资金明细
                                $detail_note = '[' . $member_data['name'] . '] 退单扣除奖励' . $field['out_money_three'];
                                $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`freeze`,`create_time`,`note`) VALUES (" . $field['out_money_three_id'] . ",11," . $field['out_money_three'] . "," . $member_money3['money'] . "," . ($member_money3['freeze']) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "')";
                                $detail_id   = $this->sql($sql);
                                if (!$detail_id) {
                                    $status = false;

                                }

                            }
                        }

                        if ($status) {
                            $commit = true;
                            $code   = 200;
                        }

                    }
                }

            }
        }

        if ($commit) {
            $this->db->commit();
        } else {
            $this->db->rollback();
        }
        return $code;

    }
    //获取会员充值明细
    public function getFinanceSister($para, $page, $pagesize = 20)
    {
        $where = " 1";
        if ($para) {

            if ($para['event']) {
                $where .= " AND `event`=" . $para['event'];
            }
            if ($para['uid']) {
                $where .= " AND `uid`=" . $para['uid'];
            }

            if ($para['start_time']) {
                $where .= " AND `create_time` >=" . $para['start_time'];

                $para['start_time'] = date("Y-m-d", $para['start_time']);
            }

            if ($para['end_time']) {
                $where .= " AND `create_time` <" . $para['end_time'];

                $para['end_time'] = date("Y-m-d", $para['end_time']);
            }
        }

        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}finance_sister WHERE " . $where;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`create_time` DESC,`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}finance_sister WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;

            $rs = $this->sql($sql);
            if ($rs) {
                foreach ($rs as &$r) {
                    if ($r['uid']) {
                        //获取用户昵称
                        $user_info = $this->getUsers($r['uid']);

                        $r['user_name'] = $user_info['realname'];

                        if ($user_info['headimgurl'] > 0) {
                            $doc             = $user_info['headimgurl'];
                            $r['headimgurl'] = $this->getDocs($doc);
                            $r['headimgurl'] = $r['headimgurl'][$user_info['headimgurl']];
                        } else {
                            $r['wechat_headimgurl'] = $user_info['wechat_headimgurl'];
                        }
                    }

                }

            }
        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
        );
    }

    //获取九戈币充值记录
    public function getFinanceCurrency($para, $page, $pagesize = 20)
    {
        $where = " 1";
        if ($para) {

            if ($para['event']) {
                $where .= " AND `event`=" . $para['event'];
            }
            if ($para['uid']) {
                $where .= " AND `uid`=" . $para['uid'];
            }

            if ($para['start_time']) {
                $where .= " AND `create_time` >=" . $para['start_time'];

                $para['start_time'] = date("Y-m-d", $para['start_time']);
            }

            if ($para['end_time']) {
                $where .= " AND `create_time` <" . $para['end_time'];

                $para['end_time'] = date("Y-m-d", $para['end_time']);
            }
        }

        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}finance_currency WHERE " . $where;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`create_time` DESC,`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}finance_currency WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;

            $rs = $this->sql($sql);
            if ($rs) {
                foreach ($rs as &$r) {
                    if ($r['uid']) {
                        //获取用户昵称
                        $user_info = $this->getUsers($r['uid']);

                        $r['user_name'] = $user_info['realname'];

                        if ($user_info['headimgurl'] > 0) {
                            $doc             = $user_info['headimgurl'];
                            $r['headimgurl'] = $this->getDocs($doc);
                            $r['headimgurl'] = $r['headimgurl'][$user_info['headimgurl']];
                        } else {
                            $r['wechat_headimgurl'] = $user_info['wechat_headimgurl'];
                        }
                    }

                }

            }
        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
        );
    }

    //获取九云币充值记录
    public function getFinanceCoins($para, $page, $pagesize = 20)
    {
        $where = " 1";
        if ($para) {

            if ($para['event']) {
                $where .= " AND `event`=" . $para['event'];
            }
            if ($para['uid']) {
                $where .= " AND `uid`=" . $para['uid'];
            }

            if ($para['start_time']) {
                $where .= " AND `create_time` >=" . $para['start_time'];

                $para['start_time'] = date("Y-m-d", $para['start_time']);
            }

            if ($para['end_time']) {
                $where .= " AND `create_time` <" . $para['end_time'];

                $para['end_time'] = date("Y-m-d", $para['end_time']);
            }
        }

        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}finance_coins WHERE " . $where;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`create_time` DESC,`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}finance_coins WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;

            $rs = $this->sql($sql);
            if ($rs) {
                foreach ($rs as &$r) {
                    if ($r['uid']) {
                        //获取用户昵称
                        $user_info = $this->getUsers($r['uid']);

                        $r['user_name'] = $user_info['realname'];

                        if ($user_info['headimgurl'] > 0) {
                            $doc             = $user_info['headimgurl'];
                            $r['headimgurl'] = $this->getDocs($doc);
                            $r['headimgurl'] = $r['headimgurl'][$user_info['headimgurl']];
                        } else {
                            $r['wechat_headimgurl'] = $user_info['wechat_headimgurl'];
                        }
                    }

                }

            }
        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
        );
    }

    public function getwithdrawStatistics($para)
    {
        $where = " 1=1 ";
        if ($para) {

            if (isset($para['status'])) {
                $where .= " AND `stat`=" . $para['status'];
            }

            if ($para['withdraw_type'] != '') {
                $where .= " AND `withdraw_type`=" . $para['withdraw_type'];
            }

            if ($para['money'] != '') {
                $where .= " AND `money` >='" . $para['money'] . "'";
            }
            if ($para['keyword'] != '') {
                if (is_numeric($para['keyword'])) {
                    $where .= " AND (`id`=" . intval($para['keyword']) . " OR `mobile`=" . $para['keyword'] . ")";
                } else {
                    $where .= " AND `realname` LIKE '%" . $para['keyword'] . "%'";
                }

            }

        }

        $sql = "SELECT `id`,`money`,`charge_fee` FROM {$this->_prefix['primary']}finance_withdraw WHERE " . $where;

        $rs          = $this->sql($sql);
        $total_money = 0;
        if ($rs) {
            foreach ($rs as $val) {

                $total_money += $val['money'];
            }
        }
        return number_format($total_money, 2, ".", "");
    }

    // 获取等待处理的提现信息
    public function getUntreatedData()
    {
        $sql  = "SELECT `id`,`money`,`realname`,`mobile`,`bank_sn`,`bank_account`,`note`,`create_time` FROM {$this->_prefix['primary']}finance_withdraw WHERE  `stat`=0 ORDER BY `id` ASC";
        $data = $this->sql($sql);

        return $data;
    }

    public function getWithdrowData($para)
    {

        $where = " 1=1 ";
        if ($para) {

            if (isset($para['status'])) {
                $where .= " AND `stat`=" . $para['status'];
            }

            if ($para['withdraw_type'] != '') {
                $where .= " AND `withdraw_type`=" . $para['withdraw_type'];
            }

            if ($para['money'] != '') {
                $where .= " AND `money` >='" . $para['money'] . "'";
            }
            if ($para['keyword'] != '') {
                if (is_numeric($para['keyword'])) {
                    $where .= " AND (`id`=" . intval($para['keyword']) . " OR `mobile`=" . $para['keyword'] . ")";
                } else {
                    $where .= " AND `realname` LIKE '%" . $para['keyword'] . "%'";
                }

            }

        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}finance_withdraw WHERE " . $where . " ORDER BY `id` DESC";

        $rs = $this->sql($sql);

        if ($rs) {
            foreach ($rs as $k => $v) {
                if ($v['uid']) {
                    //获取用户昵称
                    $user_info           = $this->getUsers($v['uid']);
                    $rs[$k]['user_name'] = $user_info['realname'];
                }

            }

        }

        return $rs;

    }

    //保存云米解冻记录
    public function saveCloud($da)
    {
        $code        = 404;
        $id          = intval($da['id']);
        $cloudDetail = $this->getCloudDetail($id);
        // print_r($cloudDetail);die;
        if ($da) {

            //设为成功
            if ($da['act'] == "done") {
                //开始事务
                $this->db->begin();
                $rollback = true;

                $pass_sn   = addslashes(htmlspecialchars(trim($da['pass_sn'])));
                $pass_time = time();
                $remark    = addslashes(htmlspecialchars(trim($da['remark'])));

                $sql = "UPDATE {$this->_prefix['primary']}member_cloud_detail SET `remark`='" . $remark . "',`pass_time`='" . $pass_time . "',`pass_sn`='" . $pass_sn . "',`status`=1 WHERE `id`=" . $cloudDetail['id'];
                $rc  = $this->sql($sql);
                if ($rc > 0) {
                    $sql     = "SELECT `money`,`freeze` FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $cloudDetail['uid'];
                    $balance = $this->db->getrow($sql);

                    //扣除冻结资金
                    $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `money`=`money`+" . $cloudDetail['money'] . ",`cloud_money`=`cloud_money`-" . $cloudDetail['money'] . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `uid`=" . $cloudDetail['uid'];
                    $rd  = $this->sql($sql);
                    if ($rd > 0) {
                        //插入资金明细
                        $detail_note = '云米解冻资金' . $money . '元';
                        $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`freeze`,`dataid`,`table_name`,`create_time`,`note`) VALUES (" . $cloudDetail['uid'] . ",13," . $cloudDetail['money'] . "," . ($balance['money'] + $cloudDetail['money']) . "," . $balance['freeze'] . "," . $cloudDetail['id'] . ",'member_cloud_detail'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "')";
                        $detail_id   = $this->sql($sql);
                        if ($detail_id > 0) {

                            $code = 200;
                            $this->db->commit();
                            $rollback = false;
                        }

                    }

                }

                if ($rollback) {
                    $this->db->rollback();
                }

            }
            //驳回
            elseif ($da['act'] == "cancel") {

                $sql = "UPDATE {$this->_prefix['primary']}member_cloud_detail SET `status`=2,`turn_time`='" . time() . "' WHERE `id`=" . $cloudDetail['id'];
                $rc  = $this->sql($sql);
                if ($rc > 0) {
                    $code = 200;

                }

            }

        }

        return $code;

    }
    //保存提现信息
    public function saveWithdraw($da)
    {

        $code = 404;
        $id   = intval($da['id']);

        $data = $this->getSingleWithdraw($id);
        //print_r($data);die;
        if ($da) {

            //设为正在处理中
            if ($da['act'] == "process") {
                $sql = "UPDATE {$this->_prefix['primary']}finance_withdraw SET `stat`='1',`last_aid`='" . $this->_auth['aid'] . "',`last_edit`='" . $_SERVER['REQUEST_TIME'] . "' WHERE `id`=" . $data['id'];
                // print_r($sql);die;
                $rc = $this->sql($sql);
                if ($rc > 0) {
                    $code = 200;
                }

            }
            //设为成功
            //设为成功
            elseif ($da['act'] == "done") {

                //开始事务
                $this->db->begin();
                $rollback    = true;
                $money       = $data['charge_fee'] + $data['money'];
                $trande_no   = addslashes(htmlspecialchars(trim($da['trade_no'])));
                $trande_fee  = number_format($da['trade_fee'], 2, ".", "");
                $trande_time = strtotime($da['trade_time']);
                //print_r($da);die;
                $trande_note = addslashes(htmlspecialchars(trim($da['trade_note'])));

                $sql = "UPDATE {$this->_prefix['primary']}finance_withdraw SET `trade_no`='" . $trande_no . "',`trade_fee`='" . $trande_fee . "',`trade_time`='" . $trande_time . "',`trade_note`='" . $trande_note . "',`stat`='2',`last_aid`='" . $this->_auth['aid'] . "',`last_edit`='" . $_SERVER['REQUEST_TIME'] . "' WHERE `id`=" . $data['id'];
                $rc  = $this->sql($sql);
                if ($rc > 0) {
                    $balance = $this->db->getrow("SELECT * FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $data['uid']);
                    if ($da['coin_type'] == 1) {
                        //扣除肽币冻结资金
                        $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `freeze`=`freeze`-" . $money . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `uid`=" . $data['uid'];
                        $rd  = $this->sql($sql);
                        if ($rd > 0) {
                            //插入肽币资金明细
                            $detail_note = '提现成功，扣除冻结的资金' . $money . '元';
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`freeze`,`dataid`,`table_name`,`create_time`,`note`) VALUES (" . $data['uid'] . ",6," . $money . "," . $balance['money'] . "," . ($balance['freeze'] - $money) . "," . $data['id'] . ",'finance_withdraw'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "')";
                            $detail_id   = $this->sql($sql);
                            if ($detail_id > 0) {

                                $code = 200;
                                $this->db->commit();
                                $rollback = false;
                            }

                        }

                    } else {

                        //扣除九云币冻结资金
                        $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `freeze_coins_money`=`freeze_coins_money`-" . $money . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `uid`=" . $data['uid'];
                        $rd  = $this->sql($sql);
                        if ($rd > 0) {
                            //插入九云币资金明细
                            $detail_note = '提现成功，扣除冻结的资金' . $money . '元';
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_coins (`uid`,`event`,`cmoney`,`money`,`freeze`,`dataid`,`table_name`,`create_time`,`note`) VALUES (" . $data['uid'] . ",6," . $money . "," . $balance['money'] . "," . ($balance['freeze_coins_money'] - $money) . "," . $data['id'] . ",'finance_withdraw'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "')";
                            $detail_id   = $this->sql($sql);
                            if ($detail_id > 0) {

                                $code = 200;
                                $this->db->commit();
                                $rollback = false;
                            }

                        }
                    }

                }

                if ($rollback) {
                    $this->db->rollback();
                }

            }
            //设为失败
            elseif ($da['act'] == "cancel") {

                //开始事务
                $this->db->begin();
                $rollback = true;

                $money = $data['charge_fee'] + $data['money'];

                $sql = "UPDATE {$this->_prefix['primary']}finance_withdraw SET `stat`='3',`last_aid`='" . $this->_auth['aid'] . "',`last_edit`='" . $_SERVER['REQUEST_TIME'] . "' WHERE `id`=" . $data['id'];
                $rc  = $this->sql($sql);
                if ($rc > 0) {
                    $balance = $this->db->getrow("SELECT `money`,`freeze`,`coins_money`,`freeze_coins_money` FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $data['uid']);

                    if ($da['coin_type'] == 1) {
                        //恢复肽币冻结资金
                        $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `money`=`money`+" . $money . ",`revenue`=`revenue`+" . $money . ",`freeze`=`freeze`-" . $money . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `uid`=" . $data['uid'];
                        $rd  = $this->sql($sql);
                        if ($rd > 0) {
                            //插入资金明细
                            $detail_note = '提现失败，解除冻结的资金' . $money . '元';
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`freeze`,`dataid`,`table_name`,`create_time`,`note`) VALUES (" . $data['uid'] . ",5," . $money . "," . ($balance['money'] + $money) . "," . ($balance['freeze'] - $money) . "," . $data['id'] . ",'finance_withdraw'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "')";
                            $detail_id   = $this->sql($sql);
                            if ($detail_id > 0) {

                                $code = 200;
                                $this->db->commit();
                                $rollback = false;
                            }

                        }
                    } else {
                        //恢复九云币冻结资金
                        $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `coins_money`=`coins_money`+" . $money . ",`freeze_coins_money`=`freeze_coins_money`-" . $money . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `uid`=" . $data['uid'];
                        $rd  = $this->sql($sql);
                        if ($rd > 0) {
                            //插入资金明细
                            $detail_note = '提现失败，解除冻结的资金' . $money . '元';
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_coins (`uid`,`event`,`cmoney`,`money`,`freeze`,`dataid`,`table_name`,`create_time`,`note`) VALUES (" . $data['uid'] . ",5," . $money . "," . ($balance['coins_money'] + $money) . "," . ($balance['freeze_coins_money'] - $money) . "," . $data['id'] . ",'finance_withdraw'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "')";
                            $detail_id   = $this->sql($sql);
                            if ($detail_id > 0) {

                                $code = 200;
                                $this->db->commit();
                                $rollback = false;
                            }

                        }

                    }

                }

                if ($rollback) {
                    $this->db->rollback();
                }

            }

        }

        return $code;

    }

    //获取单条提现信息
    public function getSingleWithdraw($id, $getuserinfo = true)
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}finance_withdraw WHERE `id`=" . intval($id);
        $data = $this->db->getrow($sql);
        if ($data && $getuserinfo) {
            $data['userinfo'] = $this->getUsers($data['uid']);
            $data['openid']   = $this->getMemberWeiXin($data['uid']);
        }
        return $data;
    }
    //获取打印注册订单详情
    public function getWithdrawPrintDetail($order_id)
    {

        $sql  = "SELECT * FROM {$this->_prefix['primary']}member_payinfo WHERE `order_id`=" . intval($order_id);
        $data = $this->db->getrow($sql);
        // 区域信息
        if ($data['tao_province_id'] > 0) {
            $region_id[] = $data['tao_province_id'];
        }

        if ($data['tao_city_id'] > 0) {
            $region_id[] = $data['tao_city_id'];
        }

        if ($data['tao_county_id'] > 0) {
            $region_id[] = $data['tao_county_id'];
        }

        if ($region_id) {
            $sql         = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `region_id` IN (" . implode(",", $region_id) . ")";
            $region_data = $this->sql($sql);
            if ($region_data) {
                foreach ($region_data as $r) {
                    $region[$r['region_id']] = $r['region_name'];
                }

                $data['region'] = $region;
            }
        }

        return $data;

    }

    //云米解冻记录
    public function getCloudList($para, $page = 1, $pagesize = 20)
    {
        $where = " 1=1 ";
        if ($para) {

            if (isset($para['status'])) {
                $where .= " AND `status`=" . $para['status'];
            }

            if ($para['money'] != '') {
                $where .= " AND `money` >='" . $para['money'] . "'";
            }

        }

        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}member_cloud_detail WHERE " . $where;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}member_cloud_detail WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;

            $rs = $this->sql($sql);

            if ($rs) {
                foreach ($rs as $k => $r) {
                    if ($r['uid']) {
                        //获取用户昵称
                        $user_info           = $this->getUsers($r['uid']);
                        $rs[$k]['user_name'] = $user_info['realname'];

                    }
                }

            }

        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
        );

    }
    //云米记录详情
    public function getCloudDetail($id)
    {
        $sql = "SELECT * FROM {$this->_prefix['primary']}member_cloud_detail WHERE `id`=" . $id;

        $data = $this->db->getrow($sql);
        if ($data['uid']) {
            $data['userinfo'] = $this->getUsers($data['uid']);
        }
        return $data;

    }
    //提现列表
    public function getWithdrawList($para, $page = 1, $pagesize = 20)
    {

        $where = " 1=1 ";
        if ($para) {

            if (isset($para['status'])) {
                $where .= " AND `stat`=" . $para['status'];
            }

            if ($para['withdraw_type'] != '') {
                $where .= " AND `withdraw_type`=" . $para['withdraw_type'];
            }

            if ($para['coin_type'] != '') {
                $where .= " AND `coin_type`=" . $para['coin_type'];
            }

            if ($para['money'] != '') {
                $where .= " AND `money` >='" . $para['money'] . "'";
            }
            if ($para['keyword'] != '') {
                if (is_numeric($para['keyword'])) {
                    $where .= " AND (`id`=" . intval($para['keyword']) . " OR `mobile`=" . $para['keyword'] . ")";
                } else {
                    $where .= " AND `realname` LIKE '%" . $para['keyword'] . "%'";
                }

            }

        }

        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}finance_withdraw WHERE " . $where;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}finance_withdraw WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;

            $rs = $this->sql($sql);

            if ($rs) {
                foreach ($rs as &$r) {
                    if ($r['uid']) {
                        //获取用户昵称
                        $user_info      = $this->getUsers($r['uid']);
                        $r['user_name'] = $user_info['realname'];

                        if ($user_info['headimgurl'] > 0) {
                            $doc             = $user_info['headimgurl'];
                            $r['headimgurl'] = $this->getDocs($doc);
                            $r['headimgurl'] = $r['headimgurl'][$user_info['headimgurl']];
                        } else {
                            $r['wechat_headimgurl'] = $user_info['wechat_headimgurl'];
                        }
                    }
                }

            }

        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
        );
    }

    //获取用户昵称和头像
    public function getUserInfo($uids)
    {

        $sql = "SELECT * FROM {$this->_prefix['primary']}member_wechat WHERE `uid` IN (" . implode(",", array_unique($uids)) . ")";

        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $user[$r['uid']] = $r;
            }
            return $user;
        } else {
            return false;
        }

    }

    public function getUsers($uid)
    {

        $sql = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $uid;

        $data = $this->db->getrow($sql);
        if ($data) {

            return $data;
        } else {
            return false;
        }

    }

    public function getUserMoney($uid)
    {

        $sql = "SELECT * FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $uid;

        return $this->db->getrow($sql);

    }

    // 统计明细信息
    public function totalDetail($da)
    {

        $sql         = "SELECT SUM(`cmoney`) AS `total` FROM {$this->_prefix['primary']}finance_detail WHERE 1";
        $da['event'] = intval($da['event']);

        if ($da['event'] > 0) {
            $sql .= " AND `event`=" . $da['event'];
        }

        if ($da['start_time'] != "") {
            $start_time = strtotime($da['start_time'] . " 0:0:0");
            $sql .= " AND `create_time`>=" . $start_time;
        }
        if ($da['end_time'] != "") {
            $end_time = strtotime($da['end_time'] . " 23:59:59");
            $sql .= " AND `create_time`<=" . $end_time;
        }
        // echo $sql;
        $money = $this->db->getone($sql);
        return $money;
    }

    public function getDocs($docid)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            $where = " WHERE `docid`=" . intval($docid);
        }

        $sql = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $doc[$r['docid']] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];

            }
            return $doc;
        } else {
            return false;
        }

    }

    // 获取设置
    public function getSetting()
    {
        $sql     = "SELECT `setting` FROM {$this->_prefix['primary']}setting ORDER BY `setting_id` DESC LIMIT 1";
        $setting = $this->db->getone($sql);
        if ($setting != "") {
            return json_decode($setting, true);
        }

    }

    // 获取微信设置
    public function getWeiXinSetting()
    {
        $sql   = "SELECT `appid` FROM {$this->_prefix['primary']}weixin_setting";
        $appid = $this->db->getone($sql);

        if ($appid != "") {
            return $appid;
        }

    }

    // 获取用户微信信息
    public function getMemberWeiXin($uid)
    {
        $sql    = "SELECT  `openid` FROM {$this->_prefix['primary']}member_wechat WHERE `uid`=" . $uid;
        $openid = $this->db->getone($sql);

        if ($openid != "") {
            return $openid;
        }

    }
    //会员开通记录导出
    public function getMemberPayinfoData($start_time = 0, $end_time = 0)
    {
        $where = "`pay_status`=2 AND `tao_name` <> '' AND `tao_mobile` <> '' AND `is_received` =1 ";
        if ($start_time > 0) {
            $where .= " AND `ctime` >= " . $start_time;
        }
        if ($end_time > 0) {
            $where .= " AND `ctime` <= " . $end_time;
        }
        $sql  = "SELECT * FROM {$this->_prefix['primary']}member_payinfo  WHERE " . $where . " ORDER BY `ctime` DESC";
        $data = $this->sql($sql);
        foreach ($data as $key => $val) {
            if ($val['uid']) {
                $uids[$val['uid']] = $val['uid'];
            }

            if (!$val['order_type']) {

                $data[$key]['order_type'] = "开通会员";
            } else {
                $data[$key]['order_type'] = "续费会员";
            }

        }
        if ($uids) {
            $sql = "SELECT `uid`,`realname` FROM {$this->_prefix['primary']}member_account WHERE `uid` IN (" . implode(",", $uids) . ")";
            $tmp = $this->sql($sql);
            if ($tmp) {
                foreach ($tmp as $r) {
                    $user[$r['uid']] = $r;
                }
            }
        }
        return array('member_payinfo' => $data, 'user' => $user);
    }
    public function getFinanceDetailData($start_time = 0, $end_time = 0, $event = 0, $keyword = '')
    {

        $where = '1';

        if ($start_time) {
            $where .= " AND fd.`create_time` >=" . $start_time;

        }

        if ($end_time) {
            $where .= " AND fd.`create_time` <" . $end_time;

        }

        if ($event) {
            $where .= " AND fd.`event`=" . $event;
        }

        if ($keyword != '') {
            if (is_numeric($keyword)) {
                $where .= " AND  (ma.`mobile`= '" . $keyword . "' OR ma.`recode`='" . $keyword . "')";
            } else {
                $where .= " AND  (ma.`realname` LIKE '%" . $keyword . "%' OR ma.`name` LIKE '%" . $keyword . "%')";
            }
        }

        $sql = "SELECT fd.*,ma.`mobile`,ma.`realname`,ma.`name`,ma.`recode` FROM {$this->_prefix['primary']}finance_detail AS fd LEFT JOIN {$this->_prefix['primary']}member_account AS ma ON ma.`uid`= fd.`uid`  WHERE " . $where . " ORDER BY  fd.`create_time` DESC";
        $rs  = $this->sql($sql);

        if ($rs) {
            foreach ($rs as $k => $r) {
                /*        if ($r['uid']) {
                //获取用户昵称
                $user_info = $this->getUsers($r['uid']);
                $rs[$k]['realname'] = $user_info['realname'];
                $rs[$k]['recode'] =  $user_info['recode'];
                $rs[$k]['mobile'] =  $user_info['mobile'];
                $rs[$k]['name'] =  $user_info['name'];
                } */

                switch ($r['event']) {
                    case 1:
                        $rs[$k]['eventS'] = "充值";
                        break;
                    case 2:
                        $rs[$k]['event'] = "消费";
                        break;
                    case 3:
                        $rs[$k]['event'] = "收入";
                        break;
                    case 4:
                        $rs[$k]['event'] = "冻结";
                        break;
                    case 5:
                        $rs[$k]['event'] = "解冻";
                        break;
                    case 6:
                        $rs[$k]['event'] = "提现";
                        break;
                    case 7:
                        $rs[$k]['event'] = "退款";
                        break;
                    case 8:
                        $rs[$k]['event'] = "分润";
                        break;
                    case 9:
                        $rs[$k]['event'] = "管理费";
                        break;

                }

                if ($r['member_level'] == 0 && $user_info['mobile'] == "") {

                    $rs[$k]['member_level'] = "用户";
                } else {

                    if ($r['member_level'] == 0) {

                        $rs[$k]['member_level'] = "游客";
                    } else if ($r['member_level'] == 1) {

                        $rs[$k]['member_level'] = "会员";
                    } else if ($r['member_level'] == 2) {

                        $rs[$k]['member_level'] = "加盟店";
                    } else if ($r['member_level'] == 3) {

                        $rs[$k]['member_level'] = "加盟仓";
                    }
                }

            }

        }

        return array('data' => $rs);
    }
    // 获取区域信息
    public function getRegion()
    {
        $sql  = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region ORDER BY `region_id` ASC";
        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $new[$r['region_id']] = $r['region_name'];
            }

            return $new;
        }
    }

    // 保存订单快递信息
    public function saveImport($da)
    {
        $code = 404;

        if (is_array($da)) {

            //print_r($da);die;
            $code = 403;
            foreach ($da as $r) {

                $order_sn     = '';
                $express_id   = "";
                $express_name = "";
                $order_sn     = addslashes(htmlspecialchars(trim($r[0])));

                $express_id   = addslashes(htmlspecialchars(trim($r[10])));
                $express_name = addslashes(htmlspecialchars(trim($r[11])));
                if ($order_sn != '' && $express_id != "" && $express_name != "") {

                    $sql      = "SELECT `order_id` FROM {$this->_prefix['primary']}member_payinfo WHERE `order_sn`='" . $order_sn . "'";
                    $order_id = $this->db->getone($sql);

                    if ($order_id) {
                        $sql = "UPDATE {$this->_prefix['primary']}member_payinfo SET `express_id`='" . $express_id . "',`express_name`='" . $express_name . "',`shipping_status`=1,`shipping_time`=" . time() . " WHERE `order_id`=" . $order_id;
                        $res = $this->sql($sql);
                    }
                }
            }

            $code = 200;
        }

        return $code;
    }

    //获取所有快递列表
    public function getExpressCompany()
    {
        $sql = "SELECT * FROM {$this->_prefix['primary']}express_company WHERE `stat`=1  ORDER BY `sort` DESC,`id` ASC";
        return $this->sql($sql);
    }
    //获取快递信息
    public function getShippingInfo($order_id)
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}member_payinfo WHERE `order_id`=" . intval($order_id);
        $data = $this->db->getrow($sql);
        return $data;
    }

    //发货
    public function saveShippingStatus($da)
    {
        $code          = 403;
        $msg           = "发货失败，请重试";
        $shipping_name = addslashes(htmlspecialchars(trim($da['shipping_name'])));
        $shipping_id   = addslashes(htmlspecialchars(trim($da['shipping_id'])));
        $order_id      = intval($da['order_id']);
        if ($shipping_name && $shipping_id && $order_id) {
            $sql  = "UPDATE {$this->_prefix['primary']}member_payinfo SET `shipping_time`=" . $_SERVER['REQUEST_TIME'] . ",`express_name`='" . $shipping_name . "',`express_id`='" . $shipping_id . "',`shipping_status`=1,`receive_time`=0 WHERE `order_id`=" . $order_id;
            $data = $this->sql($sql);
            if ($data) {
                $code = 200;
                $msg  = "发货成功";
            } else {
                $code = 430;
            }

        }
        $arr         = array();
        $arr['code'] = $code;
        $arr['msg']  = $msg;

        return $arr;
    }

    //自提
    public function saveSince($da)
    {
        $code = 403;
        $msg  = "自提失败，请重试";
        $this->db->begin();
        $rollback = true;
        $order_id = intval($da['order_id']);
        if ($order_id) {

            $sql = "UPDATE {$this->_prefix['primary']}member_payinfo SET  `shipping_status`=2,`express_id`=0,`express_name`='自提',`shipping_time`=" . time() . " WHERE `order_id`=" . $order_id;
            $rcs = $this->sql($sql);
            if ($rcs) {
                $code   = 200;
                $msg    = "自提成功";
                $commit = true;

            }

        } else {
            $code   = 403;
            $msg    = "自提失败，请重试";
            $commit = true;
        }

        if ($commit) {
            $this->db->commit();

        } else {
            $this->db->rollback();
        }

        $arr             = array();
        $arr['code']     = $code;
        $arr['msg']      = $msg;
        $arr['order_id'] = $order_id;

        return $arr;
    }

/*代理升级审核*/

    //获取列表
    public function getAgentUpgrade($para, $page, $pagesize = 20)
    {

        $where = " WHERE 1";

        if (isset($para['stat'])) {
            $where .= " AND `stat`=" . $para['stat'];
        }

        if ($para['start_time'] > 0) {
            $where .= " AND `create_time`>=" . $para['start_time'];
        }

        if ($para['end_time'] > 0) {
            $where .= " AND `create_time`<=" . $para['end_time'];
        }

        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}agent_upgrade" . $where;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}agent_upgrade" . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);
            if ($rs) {
                foreach ($rs as $k => $r) {

                    if ($r['uid'] > 0) {
                        $uids[] = $r['uid'];
                    }

                    if ($r['agent_uid'] > 0) {
                        $uids[] = $r['agent_uid'];
                    }

                }

                if ($uids) {
                    $uids = array_unique($uids);
                    // 获取微信信息
                    $sql = "SELECT `uid`,`name`,`mobile`,`wechat_headimgurl` FROM {$this->_prefix['primary']}member_account WHERE `uid` IN (" . implode(",", $uids) . ")";
                    $tmp = $this->sql($sql);
                    if ($tmp) {
                        foreach ($tmp as $r) {
                            $user[$r['uid']] = $r;
                        }
                    }

                }

            }
        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
            'user'    => $user,
        );
    }

    // 获取代理库存
    public function getAgentStock($uid)
    {
        if ($uid == 0) {
            $uid = $this->_user['uid'];
        }

        $sql = "SELECT `goods_id`,`number` FROM {$this->_prefix['primary']}agent_stock WHERE `uid`=" . $uid;
        $tmp = $this->sql($sql);
        if ($tmp) {

            foreach ($tmp as $r) {
                $data[$r['goods_id']] = $r['number'];
            }

            return $data;
        }
    }

    public function getAgentSetting($id)
    {
        // 获取设置信息
        $sql     = "SELECT `content` FROM {$this->_prefix['primary']}agent_setting WHERE `id`=" . $id;
        $content = $this->db->getone($sql);
        if ($content != "") {
            $json = json_decode($content, true);

            if ($json) {
                foreach ($json as $r) {
                    if ($r['number'] != "") {
                        $goods[$r['id']] = $r['number'];
                    }

                }

                return $goods;
            }
        }

    }

    // 保存审核
    public function saveAgentExam($da)
    {
        $code = 900;

        $id = intval($da['id']);
        $t  = intval($da['t']);

        if ($id > 0 && $t > 0) {
            $sql  = "SELECT * FROM {$this->_prefix['primary']}agent_upgrade WHERE `id`=" . $id . " AND `stat`=0";
            $data = $this->db->getrow($sql);
            if ($data) {

                // 通过审核
                if ($t == 1) {

                    $goods = $this->getAgentSetting($data['setting_id']);

                    // 如果是原点升级
                    if ($data['old_level'] > 0) {
                        
                        // 查找上一次升级的信息
                        $sql            = "SELECT `setting_id` FROM {$this->_prefix['primary']}agent_upgrade WHERE `agent_uid`=" . $data['agent_uid'] . " AND `new_level`=" . $data['old_level'] . " AND `stat`=1 ORDER BY `id` DESC LIMIT 1";
                        $old_setting_id = $this->db->getone($sql);
                        if ($old_setting_id > 0) {
                            $old_goods = $this->getAgentSetting($old_setting_id);

                            if ($old_goods && $goods) {
                                foreach ($old_goods as $goods_id => $number) {
                                    if ($goods[$goods_id] > 0) {
                                        $goods[$goods_id] -= $number;
                                    }
                                }
                            }
                        }
                    }

                    if ($goods) {

                        $stock_from = $this->getAgentStock($data['uid']);
                        $stock_to   = $this->getAgentStock($data['agent_uid']);

                        // 检查申请人库存是否足够

                        $count = 0;

                        foreach ($goods as $goods_id => $number) {
                            if ($stock_from[$goods_id] >= $number) {
                                $count += 1;
                            }
                        }

                        if ($count == count($goods)) {
                            // 开始升级
                            $this->db->begin();
                            $commit = false;
                            $code   = 403;

                            // 更新用户等级
                            $sql = "UPDATE {$this->_prefix['primary']}member_account SET `agent_level`=" . $data['new_level'] . " WHERE `uid`=" . $data['agent_uid'] . " AND `agent_level`<" . $data['new_level'];
                            $rcs = $this->sql($sql);
                            if ($rcs > 0) {

                                // 更新记录
                                $sql = "UPDATE {$this->_prefix['primary']}agent_upgrade SET `stat`=1,`last_aid`=" . $this->_auth['aid'] . ",`last_edit`=" . $_SERVER['REQUEST_TIME'] . " WHERE `id`=" . $data['id'];
                                $rcg = $this->sql($sql);
                                if ($rcg > 0) {

                                    $commit = true;

                                    foreach ($goods as $goods_id => $number) {

                                        if ($commit) {
                                            $commit = false;

                                            // 减去申请人库存
                                            $sql = "UPDATE {$this->_prefix['primary']}agent_stock SET `number`=`number`-" . $number . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `uid`=" . $data['uid'] . " AND `goods_id`=" . $goods_id;
                                            $rcs = $this->sql($sql);

                                            if ($rcs > 0) {
                                                if (isset($stock_to[$goods_id])) {
                                                    $sql = "UPDATE {$this->_prefix['primary']}agent_stock SET `number`=`number`+" . $number . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `uid`=" . $data['agent_uid'] . " AND `goods_id`=" . $goods_id;
                                                } else {
                                                    $sql = "INSERT INTO {$this->_prefix['primary']}agent_stock (`uid`,`goods_id`,`number`,`update_time`) VALUES (" . $data['agent_uid'] . "," . $goods_id . "," . $number . "," . $_SERVER['REQUEST_TIME'] . ")";
                                                }

                                                $rct = $this->sql($sql);
                                                if ($rct > 0) {

                                                    // 插入记录
                                                    $sql = "INSERT INTO {$this->_prefix['primary']}agent_stock_log (`goods_id`,`from_uid`,`to_uid`,`number`,`create_time`,`separate_type`) VALUES (" . $goods_id . "," . $data['uid'] . "," . $data['agent_uid'] . "," . $number . "," . $_SERVER['REQUEST_TIME'] . ",1)";

                                                    $rcu = $this->sql($sql);
                                                    if ($rcu > 0) {
                                                        $commit = true;
                                                    } else {
                                                        $code = 507;
                                                    }

                                                } else {
                                                    $code = 506;
                                                }

                                            } else {
                                                $code = 505;
                                            }
                                        }
                                    }

                                } else {
                                    $code = 504;
                                }

                            } else {
                                $code = 503;
                            }

                            if ($commit) {
                                $this->db->commit();
                                $code = 200;
                            } else {
                                $this->db->rollback();
                            }
                        } else {
                            $code = 501;
                        }

                    } else {
                        $code = 502;
                    }

                }
                // 驳回申请
                else {
                    $sql = "UPDATE {$this->_prefix['primary']}agent_upgrade SET `stat`=2,`last_aid`=" . $this->_auth['aid'] . ",`last_edit`=" . $_SERVER['REQUEST_TIME'] . " WHERE `id`=" . $data['id'];
                    $rcg = $this->sql($sql);
                    if ($rcg > 0) {
                        $code = 200;

                    } else {
                        $code = 403;
                    }
                }

            } else {
                $code = 404;
            }
        }

        return array(
            'code' => $code,
        );
    }

}
